package xyz.labmem.base.sys.config.mybatis

import cn.dev33.satoken.stp.StpUtil
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
import org.apache.ibatis.reflection.MetaObject
import org.springframework.stereotype.Component

/**
 * MybatisPlus插入和更新时间
 * @Author lty
 * @Date 2021/12/14 15:56
 */
@Component
class MyMetaObjectHandler : MetaObjectHandler {

    override fun insertFill(metaObject: MetaObject) {
        val data = DateUtil.date()
        if (metaObject.hasSetter("createUser"))
            setFieldValByName("createUser", getUserId(), metaObject)
        if (metaObject.hasSetter("createTime"))
            setFieldValByName("createTime", data, metaObject)
        if (metaObject.hasSetter("updateTime"))
            setFieldValByName("updateTime", data, metaObject)
        if (metaObject.hasSetter("subTime"))
            setFieldValByName("subTime", data, metaObject)
    }

    override fun updateFill(metaObject: MetaObject) {
        if (metaObject.hasSetter("updateTime"))
            setFieldValByName("updateTime", DateUtil.date(), metaObject)
    }

    private fun getUserId(): String {
        return try {
            if (StpUtil.isLogin()) {
                StpUtil.getLoginIdAsString()
            } else
                "-1"
        } catch (e: Exception) {
            "-1"
        }
    }

}